package samsung.sds.survey.surveyVote.service.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import samsung.sds.survey.surveyVote.dao.VoteSurveyResultMapper;
import samsung.sds.survey.surveyVote.model.QuestionEntity;
import samsung.sds.survey.surveyVote.model.SurveyResultEntity;
import samsung.sds.survey.surveyVote.service.VoteQuestionService;
import samsung.sds.survey.surveyVote.service.VoteSurveyResultService;
import samsung.sds.system.common.baseQuery.AbstractBaseService;
import samsung.sds.system.common.baseQuery.BaseMapper;
import samsung.sds.system.common.model.QueryParam;
import samsung.sds.system.utils.CommonTools;

/**
 * 
 * 获取投票问题及结果的service
 * 
 * @author lixin.qiu
 * @createDate 2016-01-18
 */
@Service
public class VoteSurveyResultServiceImpl extends
		AbstractBaseService<SurveyResultEntity> implements VoteSurveyResultService {

	@Autowired
	private VoteSurveyResultMapper surveyResultMapper;

	@Autowired
	private VoteQuestionService voteQuestionServiceImpl;

	@Override
	protected BaseMapper<SurveyResultEntity> getMapper() {
		return surveyResultMapper;
	}

	/**
	 * 迭代插入提交的问题的答案
	 * 
	 * @param keSet
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@Override
	public int iteratorInsertSurveyResult(Set<Entry<String, String>> keSet)
			throws UnsupportedEncodingException {
		int insertCount = 0;
		for (Iterator<Entry<String, String>> itr = keSet.iterator(); itr
				.hasNext();) {
			Entry<String, String> paraEntry = itr.next();
			SurveyResultEntity resultEntity = setResultEntityForInsert(paraEntry);
			int rlt = surveyResultMapper.insertEntity(resultEntity);
			insertCount = insertCount + rlt;
		}
		return insertCount;
	}

	/**
	 * 迭代更新提交的问题的答案
	 * 
	 * @param keSet
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@Override
	public int iteratorUpdateSurveyResult(Set<Entry<String, String>> keSet)
			throws UnsupportedEncodingException {
		int updateCount = 0;
		for (Iterator<Entry<String, String>> itr = keSet.iterator(); itr
				.hasNext();) {
			Entry<String, String> paraEntry = itr.next();

			SurveyResultEntity resultEntity = setResultEntityForUpdate(paraEntry);
			int rlt = surveyResultMapper.updateEntity(resultEntity);
			updateCount = updateCount + rlt;
		}
		return updateCount;
	}

	/**
	 * @param surveyId
	 * @return List<Question> 根据surveyId查询调查问卷的问题,问题选项及答案
	 */
	@Override
	public List<QuestionEntity> queryQuestionAndSurveyResultList(QueryParam param, Boolean isPreview) {
		String surId = (String) param.getQueryCondition().get("surveyId");
		String username = CommonTools.getSessionUserName();
		param.getQueryCondition().put("surveyId", surId);
		param.getQueryCondition().put("userName", username);
		
		List<QuestionEntity> questionList = voteQuestionServiceImpl.queryList(param);
		List<SurveyResultEntity> surveyResultList = surveyResultMapper
				.queryList(param);
		List<QuestionEntity> editLists = setFinishedValue(questionList,
				surveyResultList, isPreview);
		return editLists;
	}

	/**
	 * String类型转为BigDecimal
	 * 
	 * @param numStr
	 * @return
	 */
	private BigDecimal toBigDecimal(Object numStr) {
		return BigDecimal.valueOf(Long.parseLong((String) numStr));
	}

	/**
	 * 封装更新数据至的实体类
	 * 
	 * @param paraEntry
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private SurveyResultEntity setResultEntityForUpdate(
			Entry<String, String> paraEntry)
			throws UnsupportedEncodingException {

		String questionId = paraEntry.getKey(); // 获取参数名
		String questionAnswer = URLDecoder
				.decode(paraEntry.getValue(), "UTF-8"); // 获取参数值
		// 获取当前问题的信息
		QuestionEntity question = new QuestionEntity();
		question.setId(questionId);
		QuestionEntity questionInfo = voteQuestionServiceImpl
				.findUniqueByProperty(question);
		// 获取当前登录者
		String username = CommonTools.getSessionUserName();
		SurveyResultEntity resultEntity = setResultEntity(questionId, questionInfo,
				questionAnswer);
		resultEntity.setLastModifyTime(new Date());
		resultEntity.setLastModifyUser(username);
		return resultEntity;
	}

	/**
	 * 封装插入数据至的实体类
	 * 
	 * @param paraEntry
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private SurveyResultEntity setResultEntityForInsert(
			Entry<String, String> paraEntry)
			throws UnsupportedEncodingException {

		String questionId = paraEntry.getKey(); // 获取参数名
		String questionAnswer = URLDecoder
				.decode(paraEntry.getValue(), "UTF-8");// 获取参数值
		// 获取当前问题的信息
		QuestionEntity question = new QuestionEntity();
		question.setId(questionId);
		QuestionEntity questionInfo = voteQuestionServiceImpl
				.findUniqueByProperty(question);
		SurveyResultEntity resultEntity = setResultEntity(questionId, questionInfo,
				questionAnswer);

		resultEntity.setId(CommonTools.getKeyUUID());
		resultEntity.setCreateTime(new Date());
		resultEntity.setCreateUser(questionInfo.getCreateUser());
		return resultEntity;
	}

	/**
	 * 封装插入和更新的公共部分
	 * 
	 * @param questionId
	 * @param questionInfo
	 * @param questionAnswer
	 * @return
	 */
	private SurveyResultEntity setResultEntity(String questionId,
			QuestionEntity questionInfo, String questionAnswer) {
		// 获取当前登录者
		String username = CommonTools.getSessionUserName();
		SurveyResultEntity resultEntity = new SurveyResultEntity();
		resultEntity.setSurveyId(questionInfo.getSurveyId());
		resultEntity.setUsername(username);
		resultEntity.setQuestionId(questionId);
		resultEntity.setAnswer(questionAnswer);
		return resultEntity;
	}

	/**
	 * 处理调查问卷页面的问题及答案
	 * 
	 * @param questionList
	 * @param surveyResultList
	 * @return
	 */
	private List<QuestionEntity> setFinishedValue(List<QuestionEntity> questionList,
			List<SurveyResultEntity> surveyResultList, Boolean isPreview) {
		if (questionList != null && surveyResultList != null) {
			for (int i = 0; i < questionList.size(); i++) {
				if (questionList.get(i).getQuestionType().equals("1")
						|| questionList.get(i).getQuestionType().equals("6")) {
					setSingleOrYNValue(questionList, surveyResultList, i, isPreview);
				} else if (questionList.get(i).getQuestionType().equals("2")) {
					setMultipleSelectValue(questionList, surveyResultList, i);
				} else {
					setInputValue(questionList, surveyResultList, i);
				}
			}
		}
		return questionList;
	}

	/**
	 * 将文本框型、文本域型、数字型答案存入questionValue中
	 * 
	 * @param questionList
	 * @param surveyResultList
	 * @param i
	 */
	private void setInputValue(List<QuestionEntity> questionList,
			List<SurveyResultEntity> surveyResultList, int i) {
		for (int u = 0; u < surveyResultList.size(); u++) {
			if (surveyResultList.get(u).getQuestionId()
					.equals(questionList.get(i).getId())) {
				questionList.get(i).setQuestionValue(
						surveyResultList.get(u).getAnswer());
			}
		}
	}

	/**
	 * 将多选的答案放入questionvalue中
	 * 
	 * @param questionList
	 * @param surveyResultList
	 * @param i
	 */
	private void setMultipleSelectValue(List<QuestionEntity> questionList,
			List<SurveyResultEntity> surveyResultList, int i) {
		for (int j = 0; j < surveyResultList.size(); j++) {
			if (surveyResultList.get(j).getQuestionId()
					.equals(questionList.get(i).getId())) {
				questionList.get(i).setQuestionValue(
						surveyResultList.get(j).getAnswer());
				for (int r = 0; r < questionList.get(i).getQuestionOptionList()
						.size(); r++) {
					if (surveyResultList
							.get(j)
							.getAnswer()
							.contains(
									questionList.get(i).getQuestionOptionList()
											.get(r).getOptionValue())) {
						questionList.get(i).getQuestionOptionList().get(r)
								.setCheckValue(true);
					}
				}
			}
		}
	}

	/**
	 * 单选和YN型问题
	 * 
	 * @param questionList
	 * @param surveyResultList
	 * @param i
	 */
	private void setSingleOrYNValue(List<QuestionEntity> questionList,
			List<SurveyResultEntity> surveyResultList, int i, Boolean isPreview) {
		if(surveyResultList.size()>0){
			for (int j = 0; j < surveyResultList.size(); j++) {
				if (surveyResultList.get(j).getQuestionId()
						.equals(questionList.get(i).getId())) {
					for (int w = 0; w < questionList.get(i).getQuestionOptionList()
							.size(); w++) {
						if (questionList.get(i).getQuestionOptionList().get(w)
								.getOptionValue()
								.equals(surveyResultList.get(j).getAnswer())) {
							questionList.get(i).getQuestionOptionList().get(w)
									.setCheckValue(true);
							questionList.get(i).setQuestionValue(
									surveyResultList.get(j).getAnswer());
						}
					}
				}
			}
		}else{
			//2016.04.26 add by lidan 用于添加YN类型默认值
			if(isPreview){
				if (questionList.get(i).getQuestionType().equals("6")) {
					for (int w = 0; w < questionList.get(i).getQuestionOptionList()
							.size(); w++) {
						String validateRule = questionList.get(i).getValidateRule();
						if(questionList.get(i).getQuestionOptionList().get(w).getOptionName().equals(validateRule)){
							questionList.get(i).getQuestionOptionList().get(w).setCheckValue(true);
						}
					}
				}
			}
		}
	}
}